//
//  MainViewController.m
//  Emoticon
//
//  Created by ytkjs2 on 2020/3/26.
//  Copyright © 2020 ytk. All rights reserved.
//

#import "MainViewController.h"
#import "MainViewCell.h"
#import "SearchViewController.h"

@interface MainViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

@property (nonatomic, strong)NSMutableArray * cate_idArray;

@property (nonatomic, strong)NSMutableArray * dataSource;

@property (nonatomic, strong)NSMutableArray * topSource;

@end

@implementation MainViewController

- (NSMutableArray *)cate_idArray
{
    if (!_cate_idArray) {
        _cate_idArray = [NSMutableArray array];
    }
    return _cate_idArray;
}

- (NSMutableArray *)dataSource
{
    if (!_dataSource) {
        _dataSource = [NSMutableArray arrayWithObjects:@"",@"",@"",@"",@"",@"",@"",@"",@"", nil];
    }
    return _dataSource;
}

- (NSMutableArray *)topSource
{
    if (!_topSource) {
        _topSource = [NSMutableArray array];
    }
    return _topSource;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
//    self.automaticallyAdjustsScrollViewInsets = NO;
//     if (@available(iOS 11.0, *)) {
//            self.mainTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
//        } else {
//            self.automaticallyAdjustsScrollViewInsets = NO;
//        }
    
    UIButton * searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.frame = CGRectMake(8, 8.5, rScreenWidth - 27, 30);
    [searchBtn setTitle:@"搜索你所感兴趣的内容吧!" forState:0];
    [searchBtn setTitleColor:RGB(212, 212, 212, 1) forState:0];
    [searchBtn.layer setMasksToBounds:YES];
    [searchBtn.layer setCornerRadius:16.5];
    searchBtn.backgroundColor = [UIColor whiteColor];
    [searchBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    searchBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 0);
    [searchBtn addTarget:self action:@selector(pushSearchView) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.titleView = searchBtn;
    
    
    __weak typeof(self)weakSelf = self;
    //阻塞线程以取得 cate_id

    self.mainTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        weakSelf.topSource = [NSMutableArray array];
        weakSelf.cate_idArray = [NSMutableArray array];
        
        [PictureData getRequestWithServiceUrl:Main_Cate_id_URL parameters:@{} success:^(id  _Nonnull responseObject) {
            NSArray * arr = [responseObject objectForKey:@"data"];
            for (NSDictionary * dic in arr) {
                MainPicModel * model = [MainPicModel mj_objectWithKeyValues:dic];
                
                if ([model.name isEqualToString:@"精选"] || [model.name isEqualToString:@"最新"] || [model.name isEqualToString:@"文字表情"] || [model.name isEqualToString:@"可爱表情"])
                    [weakSelf.topSource addObject:model];
                else
                    [weakSelf.cate_idArray addObject:model];
            }
            [weakSelf addTopView];
            [weakSelf getListData];
            
            [weakSelf.mainTableView.mj_header endRefreshing];
        } failure:^(NSError * _Nonnull error) {
            [weakSelf.mainTableView.mj_header endRefreshing];
        }];
    }];
    [self.mainTableView.mj_header beginRefreshing];
}

-(void)getListData
{
    __weak typeof(self)weakSelf = self;
    
    __block NSInteger typeIndex = 0;
    

    for (MainPicModel * model in _cate_idArray) {
        
        [PictureData getRequestWithServiceUrl:Main_PicList_URL parameters:@{@"cate_id":@(model.cate_id),@"page":@(1)} success:^(id  _Nonnull responseObject) {
            NSArray * arr = [responseObject objectForKey:@"data"];
            NSMutableArray * tempArray = [NSMutableArray array];
            for (NSDictionary * dic in arr) {
                PicModel * model1 = [PicModel mj_objectWithKeyValues:dic];
                [tempArray addObject:model1];
            }
//            [weakSelf.dataSource addObject:tempArray];
            if ([model.name isEqualToString:@"魔性小人表情"]) {
                [weakSelf.dataSource replaceObjectAtIndex:0 withObject:tempArray];
            }
            if ([model.name isEqualToString:@"恶搞影视"]) {
                [weakSelf.dataSource replaceObjectAtIndex:1 withObject:tempArray];
            }
            if ([model.name isEqualToString:@"恶搞表情"]) {
                [weakSelf.dataSource replaceObjectAtIndex:2 withObject:tempArray];
            }
            if ([model.name isEqualToString:@"恶搞明星"]) {
                [weakSelf.dataSource replaceObjectAtIndex:3 withObject:tempArray];
            }
            if ([model.name isEqualToString:@"GIF动图表情"]) {
                [weakSelf.dataSource replaceObjectAtIndex:4 withObject:tempArray];
            }
            if ([model.name isEqualToString:@"熊本熊表情"]) {
                [weakSelf.dataSource replaceObjectAtIndex:5 withObject:tempArray];
            }
            if ([model.name isEqualToString:@"熊猫金馆长"]) {
                [weakSelf.dataSource replaceObjectAtIndex:6 withObject:tempArray];
            }
            if ([model.name isEqualToString:@"蚊子动漫"]) {
                [weakSelf.dataSource replaceObjectAtIndex:7 withObject:tempArray];
            }
            if ([model.name isEqualToString:@"金馆长表情"]) {
                [weakSelf.dataSource replaceObjectAtIndex:8 withObject:tempArray];
            }

            typeIndex ++;
            if (typeIndex == weakSelf.cate_idArray.count) {
                
                [weakSelf.mainTableView reloadData];
            }
        } failure:^(NSError * _Nonnull error) {

        }];
    }
    
}



-(void)addTopView
{
    CGFloat space = (rScreenWidth - 160)/8;
    NSMutableArray * tempArray = [NSMutableArray arrayWithObjects:@"",@"",@"",@"", nil];
    
    for (int i = 0; i < 4; i ++) {
        UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setFrame:CGRectMake(space + (40 + space * 2) * i, 15.5, 40, 40)];
        [btn setImage:[UIImage imageNamed:[NSString stringWithFormat:@"icon_top%d",i]] forState:0];
        btn.imageView.contentMode = UIViewContentModeScaleToFill;
        
        btn.tag = i;
        [btn addTarget:self action:@selector(topViewAction:) forControlEvents:UIControlEventTouchUpInside];
        [_topView addSubview:btn];
        
        UILabel * lab = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMidX(btn.frame) - 40, CGRectGetMaxY(btn.frame) + 4, 80, 15)];
        lab.textColor = [UIColor whiteColor];
        lab.font = [UIFont boldSystemFontOfSize:11];
        lab.text = TOP_TITLE[i];
        lab.textAlignment = NSTextAlignmentCenter;
        [_topView addSubview:lab];
        
        MainPicModel * model = _topSource[i];
        if ([model.name isEqualToString:@"最新"]) {
            [tempArray replaceObjectAtIndex:0 withObject:model];
        }
        if ([model.name isEqualToString:@"精选"]) {
            [tempArray replaceObjectAtIndex:1 withObject:model];
        }
        if ([model.name isEqualToString:@"文字表情"]) {
            [tempArray replaceObjectAtIndex:2 withObject:model];
        }
        if ([model.name isEqualToString:@"可爱表情"]) {
            [tempArray replaceObjectAtIndex:3 withObject:model];
        }
    }
    _topSource = [NSMutableArray arrayWithArray:tempArray];
}

-(void)topViewAction:(UIButton *)btn
{
    ListViewController * listVC = [[ListViewController alloc]initWithNibName:@"ListViewController" bundle:nil];
    listVC.hidesBottomBarWhenPushed = YES;
    MainPicModel * model = _topSource[btn.tag];
    listVC.title = TOP_TITLE[btn.tag];
    listVC.cate_id = model.cate_id;
    [self.navigationController pushViewController:listVC animated:YES];
}


#pragma mark <UITableViewDataSource>

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat width = (rScreenWidth - 70)/4;
    return (width + 10) * 2 + 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 35;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 15;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, rScreenWidth - 20, 35)];
    view.backgroundColor = [UIColor clearColor];
    
    UIView * cornerView = [[UIView alloc]initWithFrame:CGRectMake(0, 5, rScreenWidth - 20, 30)];
    cornerView.backgroundColor = [UIColor whiteColor];
    [self setViewCornerRadius:cornerView isHead:YES];
    [view addSubview:cornerView];
    
    UILabel * lab = [[UILabel alloc]initWithFrame:CGRectMake(15, 10, 150, 21)];
    lab.textColor = APP_THEME_COLOR;
    lab.font = [UIFont systemFontOfSize:15];
    MainPicModel * model = _cate_idArray[section];
    lab.text = model.name;
    [cornerView addSubview:lab];
    
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setFrame:CGRectMake(rScreenWidth - 60, 5, 30, 30)];
    [btn setImage:[UIImage imageNamed:@"icon_push"] forState:0];
    btn.tag = section;
    [btn addTarget:self action:@selector(pushAction:) forControlEvents:UIControlEventTouchUpInside];
    [cornerView addSubview:btn];
    
    return view;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, rScreenWidth - 20, 15)];
    view.backgroundColor = [UIColor clearColor];
    
    UIView * cornerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, rScreenWidth - 20, 10)];
    cornerView.backgroundColor = [UIColor whiteColor];
    [self setViewCornerRadius:cornerView isHead:NO];
    [view addSubview:cornerView];
    
    return view;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MainViewCell * cell = [[NSBundle mainBundle]loadNibNamed:@"MainViewCell" owner:nil options:nil][0];
    cell.controller = self;
    [cell setBtnAction:_dataSource[indexPath.section] withTag:(int)indexPath.section];
    return cell;
}

-(void)pushAction:(UIButton *)btn
{
    ListViewController * listVC = [[ListViewController alloc]initWithNibName:@"ListViewController" bundle:nil];
    listVC.hidesBottomBarWhenPushed = YES;
    MainPicModel * model = _cate_idArray[btn.tag];
    listVC.title = model.name;
    listVC.cate_id = model.cate_id;
    [self.navigationController pushViewController:listVC animated:YES];
}

-(void)btnAction:(UIButton *)btn
{
    NSLog(@"%ld",btn.tag);
    NSInteger section = btn.tag/100;
    NSInteger imageIndex = btn.tag%100;
    
    NSArray * arr = [NSArray arrayWithArray:_dataSource[section]];
    PicModel * model = arr[imageIndex];
    
    DownloadViewController * downloadVC = [[DownloadViewController alloc]initWithNibName:@"DownloadViewController" bundle:nil];
    downloadVC.dataSource = [arr mutableCopy];
    downloadVC.picIndex = imageIndex;
    downloadVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:downloadVC animated:YES];
}

-(void)pushSearchView
{
    SearchViewController * searchVC = [[SearchViewController alloc]initWithNibName:@"SearchViewController" bundle:nil];
    searchVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:searchVC animated:YES];
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat sectionHeaderHeight = 35;//这里是我的headerView和footerView的高度
    if (scrollView.contentOffset.y<=sectionHeaderHeight&& scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if(scrollView.contentOffset.y>=sectionHeaderHeight)
    {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

-(void)setViewCornerRadius:(UIView *)view isHead:(BOOL)isHead
{
    UIBezierPath *maskPath;
    if (isHead)
        maskPath= [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(10, 10)];
    else
        maskPath= [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(10, 10)];
    
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    maskLayer.path = maskPath.CGPath;
    view.layer.mask = maskLayer;
}

@end
